import DOMPurify from 'dompurify' // 记录旧数据
let oldInnerHTML = ''

function setHTML (el, value) {
  let innerHTML = value
  innerHTML = DOMPurify.sanitize(innerHTML, { ADD_ATTR: ['target'] })
  el.innerHTML = innerHTML
  // 取消img 全局的样式
  el.querySelectorAll('img').forEach(el => {
    const w = el.getAttribute('width')
    const h = el.getAttribute('height')
    el.style.width ||= w ? (w + 'px') : 'auto'
    el.style.height ||= h ? (h + 'px') : 'auto'
  })
}

const richDirective = {
  mounted (el, binding) {
    if (binding.value) {
      oldInnerHTML = binding.value
      setHTML(el, binding.value)
    }
  },
  updated (el, binding) {
    // 如果旧数据跟新数据一样 直接 return
    if (binding.value === oldInnerHTML) {
      return
    }
    if (binding.value) {
      oldInnerHTML = binding.value
      setHTML(el, binding.value)
    } else {
      oldInnerHTML = ''
      setHTML(el, '')
    }
  }
}

export default richDirective
